package com.bawei.lookfor.wxapi

import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.module_base.net.bean.login.LoginBean
import com.bawei.module_base.net.util.HttpUtils2
import com.bawei.module_base.net.util.MMKVUtil
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


class WXEntryActivity:Activity(), IWXAPIEventHandler {

    lateinit var labLogin: LoginBean
    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private val  APP_ID:String= "wx064904aa8809f5aa";
    //    // IWXAPI 是第三方app和微信通信的openApi接口
    private lateinit var api: IWXAPI

    @RequiresApi(api = Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.handleIntent(getIntent(), this);

    }


    override fun onReq(p0: BaseReq?) {

    }


    override fun onResp(p0: BaseResp?) {
        //判断状态码为0登录成功
        if (p0?.errCode == 0) {
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            val code = (p0 as SendAuth.Resp).code
            GlobalScope.launch(Dispatchers.IO) {
                val result = HttpUtils2.apiService.postWXLogin(code)
                result.result.let { it2 ->
                    if (it2 != null) {
                        labLogin = it2
                        Log.i("TAG", "onResp: " + labLogin.nickName)
                    }
                }
                if (result.status == "0000") {
                    MMKVUtil.setIsLogin(true)
                    MMKVUtil.setUser(labLogin.userId,labLogin.sessionId)
                    MMKVUtil.setUserContent(labLogin.nickName, labLogin.headPic, labLogin.sex)
                    //登录成功返回主页
                    ARouter.getInstance().build("/reverso/context_activity").navigation()
//                    startActivity(Intent(this@WXEntryActivity, MainActivity::class.java))
                }
            }
        }
    }
}